package com.rayboo.example.java8;

import java.util.Arrays;

/**
 * Parallel Sort 示例
 *
 * @author ray
 * @since 2019/07/29
 *
 * <p>Java 8在java.util包的Arrays类中引入了一个新方法parallelSort（）。引入此方法以支持数组元素的并行排序。
 *
 * <p>并行排序算法：
 * 1。将给定的数组划分为子数组，将子数组进一步划分为子数组，直到子数组达到最小粒度为止。
 * 2.子阵列由多个线程单独排序。并行排序使用Fork / Join Framework并行地对子数组进行排序。
 * 3.合并已排序的子数组。
 *
 * <p>https://beginnersbook.com/2017/10/java-8-arrays-parallel-sort-with-example/
 */
public class ParallelSortExample {

    public static void main(String[] args) {

        System.out.println("===== Example 1: Sorting Primitive Data types with Parallel Sort =====");
        int numbers[] = {22, 89, 1, 32, 19, 5};
        //Parallel Sort method for sorting int array
        Arrays.parallelSort(numbers);
        //converting the array to stream and displaying using forEach
        Arrays.stream(numbers).forEach(n->System.out.print(n+" "));


        System.out.println("\n===== Example 2: Parallel Sort by specifying the start and end index =====");
        int numbers2[] = {22, 89, 1, 32, 19, 5};
        /* Specifying the start and end index. The start index is
         * 1 here and the end index is 5. which means the the elements
         * starting from index 1 till index 5 would be sorted.
         */
        Arrays.parallelSort(numbers2, 1, 5);
        //converting the array to stream and displaying using forEach
        Arrays.stream(numbers2).forEach(n->System.out.print(n+" "));
    }
}
